const { Controller } = require("egg");
class ArticleController extends Controller {
  async list() {
    const { ctx, service } = this;
    const { pageNum, pageSize } = ctx.query;
    const query = {
      pageNum: ctx.helper.toInt(pageNum) || 1,
      pageSize: ctx.helper.toInt(pageSize) || 20,
    };
    try {
      const result = await service.article.list(query);
      this.ctx.helper.success(result);
    } catch (error) {
      this.ctx.helper.error(error);
    }
  }
  async create() {
    const { ctx, service } = this;
    const { title, detail, classify, bg, publishTime, poster } = ctx.request.body;

    const query = {
      title,
      detail,
      classify,
      bg,
      publishTime,
      poster
    };
    try {
      const result = await service.article.create(query);
      this.ctx.helper.success(result);
    } catch (error) {
      this.ctx.helper.error(error);
    }
  }

  async detail() {
    const { ctx, service } = this;
    const id = ctx.helper.toInt(ctx.params.id);
    if (!id) {
      return this.ctx.helper.error("参数异常");
    }

    try {
      const result = await service.article.getArticle({
        id: id,
      });
      this.ctx.helper.success(result);
    } catch (error) {
      this.ctx.helper.error(error);
    }
  }

  async update() {
    const { ctx, service } = this;
    const { title, detail, classify, bg, id, publishTime, poster } = ctx.request.body;
    const data = {
      title,
      detail,
      classify,
      bg,
      publishTime,
      poster
    };
    this.ctx.logger.info(ctx.helper.getData(data), "datupdatea1");
    try {
      await service.article.update({ id }, ctx.helper.getData(data));

      const res = await service.article.getArticle({
        id: id,
      });
      this.ctx.helper.success(res);
    } catch (err) {
      this.ctx.helper.error(err, "文章更新失败,请重试");
    }
  }

  async classIfyList() {
    try {
      const { service } = this;
      const result = await service.articleClassify.list();
      this.ctx.helper.success(result);
    } catch (err) {
      return this.ctx.helper.error(err, "文章分类列表查询失败");
    }
  }

  async classIfyCreate() {
    try {
      const { ctx, service } = this;
      const { value } = ctx.request.body;
      if (!value) {
        return this.ctx.helper.error("参数异常");
      }
      const result = await service.articleClassify.createOrUpdate(value);
      this.ctx.helper.success(result);
    } catch (err) {
      return this.ctx.helper.error(err, "文章分类创建失败 请稍后重试");
    }
  }

  async classIfyUpdate() {
    try {
      const { ctx, service } = this;
      const { key, value } = ctx.request.body;
      if (!value || !key) {
        return this.ctx.helper.error("参数异常");
      }
      const result = await service.articleClassify.createOrUpdate(value, key);
      this.ctx.helper.success(result);
    } catch (err) {
      return this.ctx.helper.error(err, "文章分类创建失败 请稍后重试");
    }
  }
}

module.exports = ArticleController;
